from app.config.config import settings
from app.models.theme_model import ThemeModel
import os
import csv

from app.utils.file_decode_util import check_file_encoding


class KkgcCsvService:

    def __init__(self):
        self.files = dict()

    def refresh_csv(self):
        self.files.clear()
        kkgc_path: str = settings.kkgc_path
        all_items = os.listdir(kkgc_path)
        for item in all_items:
            full_path = os.path.join(kkgc_path, item)
            if os.path.isfile(full_path):
                file_encodings = check_file_encoding(full_path)
                with open(full_path, mode='r', encoding=file_encodings) as file:
                    csv_reader = csv.reader(file, delimiter=',')  # 用逗号分隔
                    #next(csv_reader)  # 跳过第一行（表头）
                    data_dict = {row[0]: row[1] for row in csv_reader if len(row) >= 2}  # 提取第一列和第二列并作为字典返回
                    self.files[os.path.splitext(item)[0]] = data_dict
        return True

    def check_vehicle_in_csv(self, dictname: str, vehicle_no: str):
        if not self.files:
            self.refresh_csv()
        if not self.files:
            return False
        if dictname in self.files:
            data_dict: dict = self.files[dictname]
            if vehicle_no in data_dict:
                return True
        return False


kkgc_csv_service = KkgcCsvService()
